package com.tm.entity.exceptionhandler;

import com.tm.exception.BizException;
import com.tm.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;

/**
 * @author huangp
 * @create 2023-03-01 12:47
 */

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理受检异常
     * @param e
     * @return
     */
    @ExceptionHandler(BizException.class)
    public Result handlerException(BizException e){
        log.error("全局异常-->[{}]",e);
        return new Result(e.getCode(),e.getMessage(),null);
    }
    /**
     * 处理未知异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result handlerException(Exception e){

        e.printStackTrace();
        log.error("全局异常-->[{}]",e);
        return Result.error();
    }

    /**
     * 处理参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        BindingResult bindingResult = e.getBindingResult();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        //StringJoiner可以讲字符串按照指定的分隔符拼接起来
        StringJoiner sj = new StringJoiner(";");
        for (FieldError fieldError : fieldErrors) {
            sj.add(fieldError.getDefaultMessage());
        }
        return Result.error(sj.toString());
    }

}
